const express = require('express');
const WebSocket = require('ws');
const cors = require('cors');

const app = express();
const PORT = 3000;

// 启用 CORS
app.use(cors());

// 创建 HTTP 服务器
const server = app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ server });

// 存储所有连接的客户端
const clients = new Set();

wss.on('connection', (ws) => {
  console.log('New client connected');
  clients.add(ws);

  // 当收到消息时广播给所有客户端
  ws.on('message', (message) => {
    console.log(`Received: ${message}`);
    
    // 广播消息给所有客户端
    clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message.toString());
      }
    });
  });

  // 当客户端断开连接时
  ws.on('close', () => {
    console.log('Client disconnected');
    clients.delete(ws);
  });
});

app.get('/', (req, res) => {
  res.send('WebSocket Chat Server');
});